package com.chaopei.day36.service;

import com.chaopei.day36.entity.Cool;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author Corday 天涯
 * @Date 2022/4/20 16:57
 * 使用绑定的jdbc与JPA实现数据库的管理CURD
 */
@Service
public class CoolServiceImpl implements CoolService {
    // 注入一个系统的数据库操作对象PrepareStatement
    @Resource
    JdbcTemplate jt;

    @Override
    public Cool findCoolById(int id) {
        //(1)创建sql语句select id,name from cool where id=? and name=?
        String sql = "select id,name from cool where id=?";
        //(2)通过RowMapper<T>将一行记录映射成为一个实体对象
        RowMapper<Cool> rm = new BeanPropertyRowMapper<Cool>(Cool.class);
        //jt.query(sql,new Object[]{101},Cool.class);
        Cool cool = jt.queryForObject(sql, rm, id);
        //拿集合对象，如何实现
        return cool;
    }

    @Override
    public int chanageCool(int id, String name) {
        String sql = "update cool set name=? where id=?";
        int num = jt.update(sql, new Object[]{name, id});
        return num;
    }
}
